package com.lemon.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class AppClient {

    public void run() {
        //定义线程池  用来执行任务的  例如：发送消息
        EventLoopGroup group = new NioEventLoopGroup();

        //客户端启动辅助类
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap = bootstrap.group(group)
                    .remoteAddress(new InetSocketAddress(8080))
                    .channel(NioSocketChannel.class)  //实例化一个channel
                    .handler(new ChannelInitializer<SocketChannel>() {  //进行通道初始化配置
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new MyChannelHandler2());
                        }
                    });

            //尝试连接服务器 (等待连接的结果)
            ChannelFuture future = null;
            future = bootstrap.connect().sync();
            //获取channel，并且写入数据
            future.channel().writeAndFlush(Unpooled.copiedBuffer("hello netty!".getBytes(StandardCharsets.UTF_8)));
            //阻塞程序，等待接收消息
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                group.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new AppClient().run();
    }
}
